using Microsoft.AspNetCore.Http;

namespace TaskProject.Extension
{
    /// <summary>
    /// HTTP上下文扩展方法
    /// </summary>
    public static class HttpContextExtensions
    {
        /// <summary>
        /// 获取客户端IP地址
        /// </summary>
        /// <param name="context">HTTP上下文</param>
        /// <returns>客户端IP地址</returns>
        public static string GetClientIpAddress(this HttpContext context)
        {
            if (context == null)
                return "127.0.0.1";

            // 尝试从各种头部获取真实IP地址
            var ip = context.Request.Headers["X-Forwarded-For"].FirstOrDefault() ??
                     context.Request.Headers["X-Real-IP"].FirstOrDefault() ??
                     context.Request.Headers["X-Client-IP"].FirstOrDefault() ??
                     context.Connection?.RemoteIpAddress?.ToString();

            // 如果获取到的IP是本地回环地址或者为空，返回默认值
            if (string.IsNullOrEmpty(ip) || ip == "::1" || ip.StartsWith("127."))
                return "127.0.0.1";

            return ip;
        }
    }
} 